package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class EchoServer03 {
    private  DatagramSocket socket; 
    public EchoServer03(int port) throws Exception {
        socket=new DatagramSocket(port);
    }
    
    //接收请求  
    //将请求转换为字符串类型
    //根据请求返回响应
    //将响应内容封装成DatagramPacket
    //send
    public void start() throws Exception{
        System.out.println("服务器启动");
        while(true){
            //接收请求
            DatagramPacket reqPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(reqPacket);
            //将请求转换为字符串类型
            String reqString =new String(reqPacket.getData(),reqPacket.getOffset(),reqPacket.getLength());
            //根据请求返回响应
            String respString =process(reqString);
            DatagramPacket respPacket=new DatagramPacket(reqString.getBytes(), 
            reqString.getBytes().length,reqPacket.getSocketAddress());
            socket.send(respPacket);
            System.out.printf("[%s,%d],req:%s,resp:%s",reqPacket.getAddress(),reqPacket.getPort(),reqString,respString);
        }
    }

    public String process(String reqString){
        return reqString;
    }

    
    public static void main(String[] args) throws Exception {
        EchoServer03 echoServer03=new EchoServer03(9070);
        echoServer03.start();
    }
}
